//
//  CarQueryHomesViewController.m
//  XTCloud
//
//  Created by QA on 2017/3/2.
//  Copyright © 2017年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "CarQueryHomesViewController.h"
#import "MYSegmentView.h"
#import "CarQueryHomeViewCell.h"
#import "CPTouchTableTableView.h"

#import "CarProductionOrderController.h"
#import "CarQueryHomeOutViewController.h"
#import "CarQueryHomeWaitVController.h"
#import "CarQueryHomeAbnormalController.h"

#import "WebServiceCommonRequest.h"
#import "NSDictionary+DataFormat.h"

static CGFloat const headViewHeight = 150;

@interface CarQueryHomesViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong) CarQueryHomeViewCell *headImageView;
@property(nonatomic ,strong) CPTouchTableTableView *mainTableView;
@property (nonatomic, strong) MYSegmentView *RCSegView;
@property (nonatomic, strong) CarQueryHomeViewCell *lineCellView;

@property (nonatomic, assign) BOOL canScroll;
@property (nonatomic, assign) BOOL isTopIsCanNotMoveTabView;
@property (nonatomic, assign) BOOL isTopIsCanNotMoveTabViewPre;

@property (strong, nonatomic) NSMutableArray *resultLineData;

@end

@implementation CarQueryHomesViewController
@synthesize mainTableView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setTitle: @"生产排队"];
        [self addStationToNavigationItem];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.resultLineData = [NSMutableArray array];
    
    mainTableView= [[CPTouchTableTableView alloc] initWithFrame:CGRectMake(0,0,self.view.frame.size.width,self.view.frame.size.height)];
    mainTableView.delegate=self;
    mainTableView.dataSource=self;
    mainTableView.showsVerticalScrollIndicator = NO;
    mainTableView.contentInset = UIEdgeInsetsMake(headViewHeight, 0, 0, 0);
    //mainTableView.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.mainTableView];
    
    self.lineCellView = [[CarQueryHomeViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    self.lineCellView.contentView.backgroundColor = ThemeColorBlue;
    self.headImageView = self.lineCellView;
    
    [self.lineCellView drawLineViewContent:nil target:self action:nil];
    self.headImageView.frame = CGRectMake(0, -headViewHeight ,SuperWidth, headViewHeight);
    [self.mainTableView addSubview:self.headImageView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(acceptMsg:) name:@"leaveTop" object:nil];
    
    //获取页面显示数据
    [self getProductionLineNetWorkData];
}

-(void)acceptMsg:(NSNotification *)notification
{
    NSDictionary *userInfo = notification.userInfo;
    NSString *canScroll = userInfo[@"canScroll"];
    if ([canScroll isEqualToString:@"1"]) {
        _canScroll = YES;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)getProductionLineNetWorkData
{
    //站点ID
    StationInfoEntity *model = [[GetUserStationService sharedService] getSelectStationEntity];
    
    //@车辆状态（全部、出厂、待命、异常）
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeERP];
    [content setModuleType:@"CLDT_HOME_SCPD"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content setStationID:[model.stationId integerValue]];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //数据处理
        NSArray *dataArray1 = [NSArray array];
        NSArray *dataArray2 = [NSArray array];
        if(result.resultArray && result.resultArray.count>=2){
            dataArray1 = result.resultArray[0];
            dataArray2 = result.resultArray[1];
        }
        self.resultLineData = [NSMutableArray arrayWithArray:dataArray1];
        
        //生产线页面数据绘制
        [self.lineCellView drawLineViewContent:dataArray1 target:self action:@selector(productionLineView:)];
        CGRect f = self.headImageView.frame;
        f.origin.y= -headViewHeight;
        self.headImageView.frame= f;
        
        //车辆状态数据
        if(dataArray2>0){
            NSDictionary *dictionary = dataArray2[0];
            NSString *CC = [dictionary objectFormatStringForKey:@"出厂" format:@"%@\n出厂车辆" defaults:@"0\n已发车辆"];
            NSString *DM = [dictionary objectFormatStringForKey:@"待命" format:@"%@\n待命车辆" defaults:@"0\n待命车辆"];
            NSString *YC = [dictionary objectFormatStringForKey:@"异常" format:@"%@\n异常车辆" defaults:@"0\n异常车辆"];
            
            [self.RCSegView setSegmentButtonTitle:CC index:1];
            [self.RCSegView setSegmentButtonTitle:DM index:0];
            [self.RCSegView setSegmentButtonTitle:YC index:2];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
    }];
}

#pragma make - ScrollView Event

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //处理联动
    //获取滚动视图y值的偏移量
    CGFloat yOffset  = scrollView.contentOffset.y;
    
    CGFloat tabOffsetY = [mainTableView rectForSection:0].origin.y;
    CGFloat offsetY = scrollView.contentOffset.y;
    
    _isTopIsCanNotMoveTabViewPre = _isTopIsCanNotMoveTabView;
    if (offsetY>=tabOffsetY) {
        scrollView.contentOffset = CGPointMake(0, tabOffsetY);
        _isTopIsCanNotMoveTabView = YES;
    } else {
        _isTopIsCanNotMoveTabView = NO;
    }
    
    if (_isTopIsCanNotMoveTabView != _isTopIsCanNotMoveTabViewPre) {
        if (!_isTopIsCanNotMoveTabViewPre && _isTopIsCanNotMoveTabView) {
            //NSLog(@"滑动到顶端");
            [[NSNotificationCenter defaultCenter] postNotificationName:@"goTop" object:nil userInfo:@{@"canScroll":@"1"}];
            _canScroll = NO;
        }
        if(_isTopIsCanNotMoveTabViewPre && !_isTopIsCanNotMoveTabView){
            //NSLog(@"离开顶端");
            if (!_canScroll) {
                scrollView.contentOffset = CGPointMake(0, tabOffsetY);
            }
        }
    }
    
    /**
     * 处理头部视图
     */
    if(yOffset < -headViewHeight) {
        CGRect f = self.headImageView.frame;
        f.origin.y= yOffset ;
        f.size.height= -yOffset;
        f.origin.y= yOffset;
        
        //改变头部视图的fram
        self.headImageView.frame= f;
//        CGRect avatarF = CGRectMake(f.size.width/2-40, (f.size.height-headViewHeight)+56, 80, 80);
//        _avatarImage.frame = avatarF;
//        _countentLabel.frame = CGRectMake((f.size.width-Main_Screen_Width)/2+40, (f.size.height-headViewHeight)+172, Main_Screen_Width-80, 36);
    }
}

#pragma make - Action Event

- (void)productionLineView:(id)sender
{
    UITapGestureRecognizer *tapGesture = sender;
    NSInteger tag = tapGesture.view.tag;
    
    NSDictionary *dictionary = [_resultLineData objectAtIndex:tag];
    NSString *lineID = [dictionary objectFormatStringForKey:@"ID"];
    
    CarProductionOrderController *viewController = [[CarProductionOrderController alloc] initWithLineID:lineID];
    [self.navigationController pushViewController:viewController animated:YES];
}

#pragma make - Station Notification

-(void)updateStationNotification:(StationInfoEntity*)model
{
    [self.resultLineData removeAllObjects];
    [self.lineCellView drawLineViewContent:nil target:self action:nil];
    self.headImageView.frame = CGRectMake(0, -headViewHeight ,SuperWidth, headViewHeight);
    
    //获取页面显示数据
    [self getProductionLineNetWorkData];
    
    //车辆数量
    [self.RCSegView setSegmentButtonTitle:@"0\n待命车辆" index:0];
    [self.RCSegView setSegmentButtonTitle:@"0\n出厂车辆" index:1];
    [self.RCSegView setSegmentButtonTitle:@"0\n异常车辆" index:2];
    
    //车次数据更新
    CarQueryHomeWaitVController *view2 = (CarQueryHomeWaitVController*)[self.RCSegView getChildViewControllerIndex:0];
    CarQueryHomeOutViewController *view1 = (CarQueryHomeOutViewController*)[self.RCSegView getChildViewControllerIndex:1];
    CarQueryHomeAbnormalController *view3 = (CarQueryHomeAbnormalController*)[self.RCSegView getChildViewControllerIndex:2];
    [view1 updateViewData];
    [view2 updateViewData];
    [view3 updateViewData];
}

#pragma marl -tableDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return SuperHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    //添加pageView
    [cell.contentView addSubview:self.setPageViewControllers];
    
    return cell;
}

/*
 * 这里可以任意替换你喜欢的pageView
 */
-(UIView *)setPageViewControllers
{
    if (!_RCSegView) {
        CarQueryHomeOutViewController * view1= [[CarQueryHomeOutViewController alloc] init];
        CarQueryHomeWaitVController * view2= [[CarQueryHomeWaitVController alloc] init];
        CarQueryHomeAbnormalController * view3= [[CarQueryHomeAbnormalController alloc] init];
        
        NSArray *controllers=@[view2,view1,view3];
        NSArray *titleArray =@[@"0\n待命车辆",@"0\n出厂车辆",@"0\n异常车辆"];
        
        MYSegmentView * rcs= [[MYSegmentView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) controllers:controllers titleArray:titleArray ParentController:self lineWidth:SuperWidth/5 lineHeight:3.];
        _RCSegView = rcs;
    }
    return _RCSegView;
}

@end
